<template>
  <div class="about">
    <my-header @rightClick="showEit = !showEit">
      购物清单
      <template #right>
        {{ showEit ? "编辑" : "完成" }}
      </template>
    </my-header>
    <ul>
      <li v-for="(item, index) in cartList">
        <input type="checkbox" v-model="item.ischeck" @change="oneCheck" />
        <img src="../assets/img.png" alt="" />
        <section>
          <h5>{{ item.name }}</h5>
          <p>￥{{ item.price }}</p>
        </section>
        <div>
          <p @click="item.num++">+</p>
          <p>{{ item.num }}</p>
          <p @click="item.num <= 1 ? 1 : item.num--">-</p>
        </div>
      </li>
    </ul>
    <div class="foot">
      <span @click="del">
        <input type="checkbox" v-model="allCheck" @change="btnCheck" />
        {{ showEit ? "全选" : "删除选中" }}
      </span>
      <span>合计：￥{{ allPrice }}</span>
      <span class="right">去结算（{{ allNum }}）</span>
    </div>
  </div>
</template>
<script>
import myHeader from "../components/myHeader.vue";
import { computed, reactive, toRefs } from "vue";
import { useStore } from "vuex";
export default {
  components: { myHeader },
  setup(props) {
    const store = useStore();
    const data = reactive({
      cartList: computed(() => store.state.cartList),
      allCheck: store.state.cartList.every((item) => item.ischeck), // 全选
      allPrice: computed(() => {
        let price = 0;
        store.state.cartList.forEach((item) => {
          if (item.ischeck) {
            price += item.num * item.price;
          }
        });
        return price;
      }),
      allNum: computed(() => {
        let num = 0;
        store.state.cartList.forEach((item) => {
          if (item.ischeck) {
            num += item.num;
          }
        });
        return num;
      }),
      showEit: true,
    });

    // 全选的事件
    const btnCheck = () => {
      store.commit("checkAll", data.allCheck);
    };
    // 反选的事件
    const oneCheck = () => {
      data.allCheck = data.cartList.every((item) => item.ischeck);
    };

    const del = () => {
       if(data.showEit) return;
        store.commit("storeDel");
    }
    return {
      ...toRefs(data),
      btnCheck,
      oneCheck,
      del
    };
  },
};
</script>
<style lang="scss" scoped>
.about {
  height: 100%;
  background: #e9e9e9;
  overflow: hidden;
  ul {
    height: calc(100% - 100px);
    overflow: auto;
    li {
      display: flex;
      background: #fff;
      margin-top: 10px;
      padding: 10px;
      align-items: center;
      img {
        width: 80px;
        margin: 0 10px;
      }
      section {
        flex: 1;
        p {
          color: #8d3ec5;
        }
      }
    }
  }
}
.foot {
  height: 50px;
  display: flex;
  padding-left: 10px;
  justify-content: space-between;
  background: #fff;
  align-items: center;
  .right {
    padding: 0 6px;
    background: #8d3ec5;
    color: #fff;
    line-height: 50px;
  }
}
</style>
